
import cv2
import numpy as np

# ---------- 预处理 ----------
def preprocess_image(img_path):
    """读取、标准化、降噪、归一化"""
    img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
    if img is None:
        raise FileNotFoundError(f"无法读取图像: {img_path}")
    img = cv2.resize(img, (256, 256))
    img = cv2.GaussianBlur(img, (3, 3), 0)
    img = img / 255.0
    return img

# ---------- 特征提取 ----------
def extract_features(img):
    """返回3维特征：边缘占比、灰度均值、灰度方差"""
    edges = cv2.Canny(np.uint8(img * 255), 50, 150)
    edge_ratio = np.sum(edges > 0) / (256 * 256)
    gray_mean = float(np.mean(img))
    gray_var  = float(np.var(img))
    return np.array([edge_ratio, gray_mean, gray_var])
